define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');

    $.widget('rk.privateMsgNewCtrl', {
    	options:{
            orderTarget:null
        },
        eTextarea:null,
        eSubBtn:null,
    	_create: function(){
    		var me = this;
    		var elem = me.element;
            var opt = me.options;

            var btnIsEnabled = function(btn) {
                return !btn.hasClass("disabled");
            },
            btnEnable = function(btn) {
                btn.removeClass("disabled");
            },
            btnDisable = function(btn) {
                if (!btn.hasClass("disabled")) {
                    btn.addClass("disabled");
                }
            };

            var newMsgTpl = require('page/tmpl/privatemsg/privateNewMsg.tpl');
            var newMsgHtml = rk.templateText(newMsgTpl);
            elem.append(newMsgHtml);

            var eTextarea = elem.find("li.message_sent_li>textarea");
            var eSubBtn = elem.find("div.sent_button>a.pg-btn-blue");

            me.eTextarea = eTextarea;
            me.eSubBtn = eSubBtn;

            var filequeue = $('#pm_new_filequeue');
            var picUploadBtn = elem.find("div.pic_attachment");
            var fileUploadBtn = elem.find("div.file_attachment");
            //设置一个id，是uploadify必须的
            picUploadBtn.attr("id", "pm_new_pic_attachment");
            fileUploadBtn.attr("id", "pm_new_file_attachment");

            var modifyMessageBoxHeight = function(){
                if(eTextarea.css('height').slice(0,-2) > 49){
                    eTextarea.css('overflow-y','scroll');
                }else{
                    eTextarea.css('overflow-y','hidden');
                }
            }

            eTextarea.autoTextarea({
                maxHeight: 75,
                minHeight: 49
            }).bind("input propertychange", function() {
                var et = $(this);
                if (et.val().length > 0) {
                    btnEnable(eSubBtn);
                } else {
                    if (!elem.data('uploadFile')) {
                        btnDisable(eSubBtn);
                    }
                }
            }).on("keydown",function(evt){
                if(evt.keyCode === 13 && !evt.ctrlKey && !evt.shiftKey && !evt.altKey){
                    evt.preventDefault();
                    eSubBtn.trigger('click');
                }
                if(evt.keyCode === 13 && (evt.ctrlKey || evt.shiftKey || evt.altKey)){
                    eTextarea.val($.trim(eTextarea.val())+"\r\n");
                }
            }).bind("paste cut keydown keyup focus blur",function(){
                modifyMessageBoxHeight();
            });

            $("#pm_new_autocomplete").find(':input').snsmultipeopleselector({
                position: { 
                    my: 'left top-248',
                    at: 'left top',
                    of: "#pm_new_autocomplete"
                },
                excludeUsers:SESSION.user.id
            });

            eSubBtn.on("click", function(evt) {
                var eb = $(this);
                evt.preventDefault();
                if (btnIsEnabled(eb)) {
                    var cval = $.trim(eTextarea.val());
                    if(cval.length === 0 && !elem.data('uploadFile')){
                        eTextarea.val("");
                        return false;
                    }
                    btnDisable(eSubBtn);
                    eSubBtn.text(rk.i18n('PRIVATEMSG_SENDING') + "...");
                    if (cval.length > 1000) {
                        rk.noticeError(rk.i18n('PRIVATEMSG_CONTENT_MAX_ERROR'));
                        btnEnable(eSubBtn);
                        eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                        return false;
                    }
                    var memberEl = $("#pm_new_autocomplete").find(':input');
                    var memberIdList = (memberEl.data('wtype') == 'snsmultipeopleselector' ? memberEl.snsmultipeopleselector('val') : '') || [];
                    if (memberIdList.length === 0) {
                        rk.noticeError(rk.i18n('PRIVATEMSG_MAST_ONE_OR_MORE_PARTICIPANTS'));
                        btnEnable(eSubBtn);
                        eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                        return false;
                    }
                    var params = {
                        memberIds: memberIdList.join(","),
                        content: cval
                    };
                    var uploadFile = elem.data('uploadFile');
                    if (uploadFile) {
                        var pmtype = 1;
                        if (uploadFile.fileType == 0) {
                            pmtype = 2;
                        }
                        params = $.extend({}, params, {
                            uploadFileName: uploadFile.name,
                            pmType: pmtype,
                            uploadFileUrl: uploadFile.fileUrl,
                            uploadFileLength: uploadFile.fileLength
                        });
                    }

                    if(memberIdList.length === 1 && memberIdList[0] == window.SESSION.user.id){
                        rk.noticeError('您不能给自己发送企业微信');
                        btnEnable(eSubBtn);
                        eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                        return false;
                    }

                    $.postJson("/json/sns_privatemsg/add.action", params).done(function(json) {
                        if (json.status) {
                            rk.noticeError(json.status);
                            btnEnable(eSubBtn);
                            eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                            return;
                        }

                        if (json.data) {
                            me.destroy();
                            $('#privatemsg').privateMsgCtrl("reorderList", json.data.pmId,0,0,'open');
                            btnDisable(eSubBtn);
                        }else{
                            btnEnable(eSubBtn);
                        }
                        eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                    }).fail(function(def, code, message) {
                        eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                        btnEnable(eSubBtn);
                    });
                    //if(window._hmt){_hmt.push(['_trackEvent', 'privatemsg', 'send_new_message', window.SESSION.tenantName]);}
                }
            });

            
            //uploads
            picUploadBtn.uploadify({
                swf: '/swf/uploadify.swf',
                uploader: '/json/global_uploadify/img-upload.action',
                auto: true,
                buttonClass: 'pic_attachment',
                buttonCursor: 'hand',
                buttonImage: '',
                buttonText: rk.i18n('PRIVATEMSG_PICTURE'),
                fileObjName: 'uploadFile',
                fileSizeLimit: '5MB',
                fileTypeDesc: rk.i18n('PRIVATEMSG_PICTURE'),
                fileTypeExts: '*.jpg;*.gif;*.png;*.JPEG;*.BMP',
                removeCompleted: false,
                successTimeout: 30,
                multi: false,
                queueID: "pm_new_filequeue",
                width: "auto",
                height: "auto",
                itemTemplate: '<div class="upload_popup" id="${fileID}"><div class="uploadifyQueue" style="display: block;"><div class="uploadifyQueueItem completed clear"><span class="fileName">${fileName} (${fileSize})</span><span class="data"></span></div><div class="uploadify-progress"><p class="nc_upload_processing">'+rk.i18n('PRIVATEMSG_UPLOADING')+'</p></div></div><a href="javascript:;" fileID="${fileID}" class="close" title="'+rk.i18n('PRIVATEMSG_CLOSE')+'"></a></div>',
                onSelect: function(file) {
                    var d = elem.data('uploadFile');
                    if (d) {
                        picUploadBtn.uploadify("cancel", d.id);
                        $("#" + d.id).remove();
                    }
                },
                onCancel: function(file) {
                    elem.removeData('uploadFile');
                    if ($.trim(eTextarea.val()) < 1) {
                        btnDisable(eSubBtn);
                    }
                },
                onUploadStart: function(file) {
                    picUploadBtn.uploadify('settings', 'formData', {
                        'pageTenantId': SESSION.tenantId,
                        'uploadFileName': file.name,
                        'uploadContentType': file.type.slice(1)
                    });
                    filequeue.show();
                    filequeue.find(".nc_upload_processing").show();
                    filequeue.find("div.show_attachment").hide();
                },
                onUploadSuccess: function(file, data, response) {
                    data = $.parseJSON(data);
                    if (data.status == 0) {
                        elem.data('uploadFile', $.extend(data.data.returnParams, {
                            fileType: 1
                        }, file));
                        filequeue.find(".nc_upload_processing").hide();
                        filequeue.find("div.show_attachment").show();
                        btnEnable(eSubBtn);
                        filequeue.find('a.close').on('click',function(){
                            var target = $(this);
                            picUploadBtn.uploadify('cancel',target.attr('fileID'));
                        });
                    } else {
                        rk.noticeError(rk.i18n('PRIVATEMSG_UPLOAD_ERROR'));
                        picUploadBtn.uploadify("cancel", file.id);
                    }
                },
                onDialogClose: function(queueData) {
                    queueData.files = {};
                    queueData.uploadQueue.splice(0, queueData.uploadQueue.length);
                }
            });
            fileUploadBtn.uploadify({
                swf: '/swf/uploadify.swf',
                uploader: '/json/global_uploadify/files-upload.action',
                auto: true,
                buttonClass: 'file_attachment',
                buttonCursor: 'hand',
                buttonImage: '',
                buttonText: rk.i18n('PRIVATEMSG_FILE'),
                fileObjName: 'uploadFile',
                fileSizeLimit: '80MB',
                fileTypeDesc: rk.i18n('PRIVATEMSG_FILE'),
                fileTypeExts: '',
                removeCompleted: false,
                successTimeout: 30,
                multi: false,
                queueID: "pm_new_filequeue",
                width: "auto",
                height: "auto",
                itemTemplate: '<div class="upload_popup" id="${fileID}"><div class="uploadifyQueue" style="display: block;"><div class="uploadifyQueueItem completed clear"><span class="fileName">${fileName} (${fileSize})</span><span class="data"></span></div><div class="uploadify-progress"><p class="nc_upload_processing">'+rk.i18n('PRIVATEMSG_UPLOADING')+'</p></div></div><a href="javascript:;" fileID="${fileID}" class="close" title="'+rk.i18n('PRIVATEMSG_CLOSE')+'"></a></div>',
                onSelect: function(file) {
                    var d = elem.data('uploadFile');
                    if (d) {
                        fileUploadBtn.uploadify("cancel", d.id);
                        $("#" + d.id).remove();
                    }
                },
                onCancel: function(file) {
                    elem.removeData('uploadFile');
                    if ($.trim(eTextarea.val()) < 1) {
                        btnDisable(eSubBtn);
                    }
                },
                onUploadStart: function(file) {
                    elem.data("uploadFileId", (file.id));
                    fileUploadBtn.uploadify('settings', 'formData', {
                        'pageTenantId': SESSION.tenantId,
                        'uploadFileName': file.name,
                        'uploadContentType': file.type.slice(1)
                    });
                    filequeue.show();
                    filequeue.find(".nc_upload_processing").show();
                    filequeue.find("div.show_attachment").hide();
                },
                onUploadSuccess: function(file, data, response) {
                    data = $.parseJSON(data);
                    if (data.status == 0) {
                        elem.data('uploadFile', $.extend(data.data.returnParams, {
                            fileType: 0
                        }, file));
                        filequeue.find(".nc_upload_processing").hide();
                        filequeue.find("div.show_attachment").show();
                        btnEnable(eSubBtn);
                        filequeue.find('a.close').on('click',function(){
                            var target = $(this);
                            fileUploadBtn.uploadify('cancel',target.attr('fileID'));
                        });
                    } else {
                        rk.noticeError(rk.i18n('PRIVATEMSG_UPLOAD_ERROR'));
                        fileUploadBtn.uploadify("cancel", file.id);
                    }
                },
                onDialogClose: function(queueData) {
                    queueData.files = {};
                    queueData.uploadQueue.splice(0, queueData.uploadQueue.length);
                }
            });
            elem.data("picUploadBtn", picUploadBtn);
            elem.data("fileUploadBtn", fileUploadBtn);
            //close
            elem.find('.pm_close').click(function(){
                me.destroy();
            });
            elem.show();
        },
        _init: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            //depart selector
            if(opt.orderTarget !== null){
                if($("#pm_new_autocomplete").find(':input').data('wtype') == 'snsmultipeopleselector'){
                    $("#pm_new_autocomplete").find(':input').snsmultipeopleselector('addItem',opt.orderTarget);
                }else{
                    var st = setInterval(function(){
                        if($("#pm_new_autocomplete").find(':input').data('wtype') == 'snsmultipeopleselector'){
                            clearInterval(st);
                            $("#pm_new_autocomplete").find(':input').snsmultipeopleselector('val',opt.orderTarget);
                        }
                    },100);
                }
            }

            elem.show();
    	},
        destroy: function(){
            var me = this;
            var elem = me.element;

            $("#pm_new_autocomplete").find(':input').snsmultipeopleselector('clear');

            elem.hide();

            me.eTextarea.val("");
            //clear uploadify
            var picUploadBtn = elem.data("picUploadBtn"),
                fileUploadBtn = elem.data("fileUploadBtn");
            var uploadFile = elem.data('uploadFile');
            if (uploadFile) {
                if (uploadFile.fileType == 1) {
                    picUploadBtn.uploadify("cancel", uploadFile.id);
                }
                if (uploadFile.fileType == 0) {
                    fileUploadBtn.uploadify("cancel", uploadFile.id);
                }
            }
            //disable button
            var btn = me.eSubBtn;
            if (!btn.hasClass("disabled")) {
                btn.addClass("disabled");
            }

            elem.find('.ui-autocomplete-input ').attr('placeholder',rk.i18n('PRIVATEMSG_ENTER_AND_CHOOSE'));

            elem.find('.ui-autocomplete-box').find('dt').remove();
        }
    });
});